package com.ustze.ocr.type.ali.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ustze.ocr.domain.AliOcrResponse;
import com.ustze.ocr.domain.vo.DayDispatchStatistic;
import com.ustze.ocr.domain.vo.DispatchDetailVo;
import com.ustze.ocr.enums.DispatchPdfEnum;
import com.ustze.ocr.properties.OcrProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@RequiredArgsConstructor
@Slf4j
public class AliOcrUtils {


    private final OcrProperties ocrProperties;

    public com.aliyun.ocr_api20210707.Client createClient(){
        try {
            com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                    // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                    .setAccessKeyId(ocrProperties.getAli().getSecretId())
                    // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                    .setAccessKeySecret(ocrProperties.getAli().getSecretKey());
            config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
            return new com.aliyun.ocr_api20210707.Client(config);
        } catch (Exception e) {

            if (log.isDebugEnabled()) {
                log.debug("创建阿里ocr 客户端错误");
            }
            throw new RuntimeException(e);
        }
    }

    public static DispatchDetailVo buildVo(String text) {
        JSONObject jsonObject = JSONObject.parseObject(text);
        String prismTablesInfo = jsonObject.getString("prism_tablesInfo");
        JSONArray jsonObjectTable = JSONArray.parseArray(prismTablesInfo);
        String prismTablesInfoOne = jsonObjectTable.getString(0);
        JSONObject tableOne = JSONObject.parseObject(prismTablesInfoOne);
        String cellInfos = tableOne.getString("cellInfos");
        List<AliOcrResponse> aliOcrResponses = JSONArray.parseArray(cellInfos, AliOcrResponse.class);
        // 按行分组
        Map<Integer, List<AliOcrResponse>> rowsMap = aliOcrResponses.stream().collect(Collectors.groupingBy(AliOcrResponse::getYec));

        // 获取基础对象
        DayDispatchStatistic dispatchStatistic = DayDispatchStatistic.build();
        DispatchDetailVo dispatchVo = DispatchDetailVo.buildVo(dispatchStatistic);
        aliOcrResponses.stream().filter(data -> "备注".equals(data.getWord())).findFirst().ifPresent(responseVo -> {
            aliOcrResponses.stream().filter(remark ->
                    remark.getXsc().equals(responseVo.getXsc())
                            && remark.getXec().equals(responseVo.getXec())
                            && !remark.getYsc().equals(responseVo.getYsc())
            ).findFirst().ifPresent(responseVo2 -> {

                dispatchVo.setRemark(responseVo2.getWord());
            });
        });

        rowsMap.forEach((type, faceList) -> {
            DispatchPdfEnum dispatchPdfEnum = DispatchPdfEnum.getCode(type);
            if (null != dispatchPdfEnum) {
                List<AliOcrResponse> responses = faceList.stream().filter(data -> DispatchPdfEnum.getType(data.getYsc(), data.getYec())).collect(Collectors.toList());
                dispatchPdfEnum.getBuildData().accept(responses, dispatchVo);
            }
        });

        return dispatchVo;
    }
}
